package com.user.service;

import com.apkInfo.util.ApkUtil;
import com.data.bean.Account;
import com.data.entity.TempUpdateApk;
import com.data.util.CheckDataUtils;
import com.data.util.DatabaseIdUtils;
import com.data.util.FileResumeUtils;
import com.data.util.FinalStringUtils;
import com.mysql.jdbc.StringUtils;
import com.user.bean.*;
import com.user.dbdao.SoftwareDao;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.util.*;

import static com.data.util.FinalStringUtils.*;

/**
 * 软件上传服务层
 *
 * @author:HingLo
 * @create 2017-09-15 9:53
 **/
@Service
public class SoftwareService {
    private static Logger logger = Logger.getLogger(SoftwareService.class);
    @Autowired
    private SoftwareDao softwareDao;


    /**
     * 查询标签类型
     *
     * @return
     */
    public List<?> findSoftwareAction() {
        return softwareDao.findSoftwareDao();
    }

    /**
     * 上传软件的临时文件处理方法
     *
     * @param path 软件要存入的名称与路径
     * @param file 文件
     * @return
     */

    public Map<String, Object> uploadTempSoftwareService(String path, CommonsMultipartFile file, String s) {
        Map<String, Object> map;
        //查看apk在我们的数据库中是否存在
        if (s.equals("apk")) {
            DiskFileItem fi = (DiskFileItem) file.getFileItem();
            File files = fi.getStoreLocation();
            map = ApkUtil.getApkInfoUtils(files);

            //检测该apk是否已经存在在我们的品台
            String packageName = (String) map.get(PACKAGENAME);//软件的信息中的包名称
            if (packageName == null) {
                //如果是null，也就是获取不到程序的包名称，直接返回，提示
                map.put(ERROR, "获取不到该App的包名称");
                return map;
            }
            if (!softwareDao.checkApkExistenceDao(packageName)) {//检测该软件是否在系统中
                if (FileResumeUtils.uploadFile(path, file)) {//保存文件到临时文件中
                    return map;
                } else {//复制到临时文件夹失败
                    map.put(ERROR, "软件上传失败");
                    return map;
                }
            } else {//上传的软件已经在我们的系统中
                map.put(ERROR, "该APP的包名称: " + packageName + " 已经在我们的系统中");
                return map;
            }
        } else {//图片保存
            map = new HashMap<>();
            return FileResumeUtils.uploadFile(path, file) ? map : null;
        }
    }

    public Map uploadTempSoftwareService(CommonsMultipartFile file, String s, String rid) {
        Map<String, Object> map;
        //查看apk在我们的数据库中是否存在
        if (s.equals(".apk")) {
            DiskFileItem fi = (DiskFileItem) file.getFileItem();
            File files = fi.getStoreLocation();
            map = ApkUtil.getApkInfoUtils(files);
            //软件的信息中的包名称
            String packageName = ((String) map.get(PACKAGENAME)).toLowerCase();
            if (packageName == null) {
                //如果是null，也就是获取不到程序的包名称，直接返回，提示
                map.put(ERROR, "获取不到该App的包名称");
                return map;
            }
            //检测该软件是否在系统中
            if (softwareDao.checkApkExistenceDao(packageName, rid)) {
                StringBuilder path = new StringBuilder(FinalStringUtils.APKPATH).append("apk/").append(map.get("md5")).append(s);
                //保存文件文件夹下
                if (FileResumeUtils.uploadFile(path.toString(), file)) {
                    return map;
                } else {//复制到临时文件夹失败
                    map.put(ERROR, "软件上传失败");
                    return map;
                }
            } else {//上传的软件已经在我们的系统中
                map.put(ERROR, "该APP的包名称: " + packageName + " 不在我们的系统中,上传失败");
                return map;
            }
        } else {
            map = new HashMap<>();
            return FileResumeUtils.uploadFile(rid, file) ? map : null;
        }
    }


    /**
     * @param app       软件对象
     * @param uid       用户账号的id
     * @param sid       session id
     * @param appDetail App详情
     * @param img       截图的名称，是一个用逗号隔开的多个名称
     * @param file      应用图标，小图与中图标
     * @param menu      应用的标签
     * @return
     */
    public boolean softwareUploadService(App app, String uid, String sid, AppDetail appDetail, String img, String menu, CommonsMultipartFile file[]) {
        if (!CheckDataUtils.stringUtils(uid, sid, img)) {
            return false;
        }

        uid = uid.trim();
        sid = sid.trim();

        String image[] = img.split(",");
        int len = image.length;
        //截图数量不对就直接结束
        if (len > 5 || len < 2) {
            return false;
        }

        //App 基本处理完成
        //软件id
        String rid = DatabaseIdUtils.getDataIdOne();
        app.setId(rid);
        app.setCtime(new Date());
        //文件是否真正的复制到最终文件中
        if (!FileResumeUtils.readUploadTempFileUtils(sid, app.getMd5())) {
            return false;
        }


        //处理app的详细信息
        appDetail.setId(DatabaseIdUtils.getDataIdOne());
        appDetail.setUid(uid);
        appDetail.setSid(rid);

        //复制文件到文件夹中
        FileResumeUtils.copyIcon(image, rid, sid);
        //上面是截图处理
        List<AppIcon> list = new ArrayList<>();
        //小图标处理
        list = imageDetail(file, rid, list, uid, image, true);
        //应用标签处理
        String menus[] = menu.split(",");
        String fid = app.getMenuid();
        List<AppMenu> menuList = new ArrayList<>();
        for (String s : menus) {
            AppMenu appMenu = new AppMenu();
            appMenu.setFid(fid);
            appMenu.setMid(s);
            //软件的id
            appMenu.setRid(rid);
            appMenu.setId(DatabaseIdUtils.getDataIdOne());
            menuList.add(appMenu);

        }

        //下载量表初始化
        AppDownload appdownload = new AppDownload();
        appdownload.setDown(0);
        appdownload.setId(rid);
        ///保存软件信息了
        return softwareDao.saveSoftwrreMassage(app, appDetail, appdownload, list, menuList);

    }

    /**
     * @param uid  用户id
     * @param rid  软件的id
     * @param type 图片类型
     * @return
     */
    private AppIcon getAppIcon(String uid, String rid, String type) {
        AppIcon icon = new AppIcon();
        icon.setId(DatabaseIdUtils.getDataIdOne());
        //图表类型
        icon.setTypes(type);
        icon.setUid(uid);
        icon.setRid(rid);
        return icon;
    }

    /**
     * 删除id
     *
     * @param id
     * @return
     */
    public boolean deleteSoftwareService(String id, String md5) {
        if (softwareDao.deleteSoftwareService(id)) {
            //删除文件中图片
            logger.debug("删除文件");
            //临时文件的路径
            StringBuilder path = new StringBuilder(FinalStringUtils.IMAGEPATH).append(id).append("/");
            if (FileResumeUtils.deleteDir(path.toString())) {
                //删除apk文件
                path = new StringBuilder(FinalStringUtils.APKPATH).append("apk/").append(md5).append(".apk");
                return FileResumeUtils.deleteFile(path.toString());
            }
            return false;

        }
        return false;
    }

    public boolean downOfflineSoftwareService(String id, String contents) {
        id = id.trim();
        contents = contents.trim();

        boolean bool;
        AppOffline appOffline = new AppOffline();
        appOffline.setId(DatabaseIdUtils.getDataIdOne());
        appOffline.setCtime(new Date());
        appOffline.setRid(id);
        appOffline.setContent(contents);
        appOffline.setState(false);
        bool = softwareDao.downOfflineSoftwareDao(id, appOffline);
        return bool;
    }


    public List<?> findSoftwareInfoService(String id, int k) {
        //检测传入的id是否有效，如果无效就直接返回
        if (!CheckDataUtils.stringUtilsID(id)) {
            return null;
        }

        //第一步查看软件的信息
        id = id.trim();
        switch (k) {
            case 1:
                return softwareDao.findSoftwareInfoDao(id);
            case 2:
                return softwareDao.findSoftwareIconDao(id);
            case 3:
                return softwareDao.findSoftwareMenuDao(id);
            default:
                return null;
        }

    }


    public boolean softwareUpdateUploadService(CommonsMultipartFile[] file, Map<String, Object> map, Account account, TempUpdateApk tempUpdateApk) {
        //设置软件的大小
        float size = (Float) map.get(SOFTWARESIEZE);
        //设置软件版本
        String version = (String) map.get(VERSIONNAME);
        //设置软件MD5值
        String md5 = (String) map.get(MD5);
        int state;
        //内置上传用户
        if (account.getTypes() == FinalStringUtils.BUILT_ADMIN) {
            //如果是内置账号上传用户，默认为软件为激活状态
            state = FinalStringUtils.ACTIVE;
        } else {
            //其他账号上传的用户，设置App的状态需要审核
            state = FinalStringUtils.DEFAULT;
        }
        String name = tempUpdateApk.getName();
        String content = tempUpdateApk.getContent();
        String introduce = tempUpdateApk.getIntroduce();
        String images = tempUpdateApk.getImage();
        String vcontent = tempUpdateApk.getVcontent();
        //软件的id
        String rid = tempUpdateApk.getRid();
        //组装要修改的软件信息
        String uid = account.getId();
        Object[] object = {name, content, introduce, vcontent, size, version, md5, state, rid, uid};
        List<AppIcon> list = new ArrayList<>();

        String[] image = images.split(",");

        //图标处理
        list = imageDetail(file, rid, list, uid, image, false);

        return softwareDao.softwareUpdateUpload(list, rid, uid, object);

    }


    /***
     * 私有的图片处理
     * @param file
     * @param rid
     * @param list
     * @param uid
     * @param image
     * @param type
     * @return
     */
    private List<AppIcon> imageDetail(CommonsMultipartFile[] file, String rid, List<AppIcon> list, String uid, String[] image, boolean type) {
        //截图处理
        for (String anImage : image) {
            if (!StringUtils.isNullOrEmpty(anImage)) {
                AppIcon icon = this.getAppIcon(uid, rid, FinalStringUtils.IAMGEBIG);
                icon.setName(anImage);
                list.add(icon);
            }

        }
//图标处理
        for (int i = 0; i < file.length; i++) {
            CommonsMultipartFile f = file[i];
            if (f != null && !f.isEmpty()) {
                String filename = f.getOriginalFilename();
                //获取文件的后缀
                String s = filename.substring(filename.lastIndexOf("."));
                if (CheckDataUtils.iconUtils(s)) {
                    String bool = FileResumeUtils.saveMinIcon(f, rid);
                    if (bool != null) {
                        AppIcon icon;
                        if (i == 0) {
                            icon = this.getAppIcon(uid, rid, FinalStringUtils.IAMGEMIN);
                        } else {
                            icon = this.getAppIcon(uid, rid, FinalStringUtils.IAMGEMED);
                        }
                        icon.setName(bool);
                        list.add(icon);
                    }
                }
            }

        }
        return list;
    }

    /**
     * 根据软件的Id来查询软件的信息
     *
     * @param rid
     * @return
     */
    public App findSoftwareInfoService(String rid) {

        return softwareDao.findSoftwareDao(rid);

    }
}
